<template>
  <el-form
    ref="formRef"
    v-loading="formLoading"
    :model="formData"
    :rules="formRules"
  >       
      <el-form-item label="申请原因" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
  
  </el-form>
  <el-form
ref="itemRef"
    v-loading="formLoading"
    :model="depPurchaseItems"
    :rules="itemRules">
  <el-tabs v-model="subTabsName">
      <el-tab-pane label="科室采购申请项" name="depPurchaseItem">
    
    <el-table :data="depPurchaseItems" class="-mt-10px">
      <el-table-column label="序号" type="index" width="100" />


          <el-table-column label="产品名称" min-width="180">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productId`" :rules="itemRules.productId" class="mb-0px!">
            <!-- remote远程搜索组件  将select选择器改为输入框  :filter-method 键入监听方法    filterable 键入组件 -->
        <el-select
          v-model="row.productName"
          clearable
          remote
          :filter-method="hospitalFilter"
          filterable
          placeholder="请选择产品名称"
          @change="onChangeProduct($event, row)"
          class="!w-240px"
        >
          <el-option
            v-for="item in supplierList"
            :key="item.id"
            :label="item.fullName"
            :value="item.id"
          />
        </el-select>
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="产品单位" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productUnitName`"  class="mb-0px!">
            <el-input v-model="row.productUnitName" placeholder="请输入产品单位"   disabled/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品单位" min-width="150" v-if="false">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productUnitId`"  class="mb-0px!">
            <el-input v-model="row.productUnitId" placeholder="请输入产品单位"   disabled/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品规格" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productStandards`" class="mb-0px!">
            <el-input v-model="row.productStandards" placeholder="请输入产品规格"   disabled/>
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="产品单价" fixed="right" min-width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productPrice`" class="mb-0px!">
            <el-input-number
              v-model="row.productPrice"
              controls-position="right"
              :min="0.01"
              disabled
              :precision="2"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
       <el-table-column label="数量" prop="count" fixed="right" min-width="140">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" :rules="itemRules.count" class="mb-0px!">
            <el-input-number
              v-model="row.count"
              controls-position="right"
              :min="1"
              :precision="0"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
        <el-table-column label="总价" prop="totalPrice" fixed="right" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.totalPrice`" class="mb-0px!">
            <el-input
              disabled
              v-model="row.totalPrice"
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </template>
      </el-table-column>


      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link><Icon icon="ep:delete" />删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加科室采购申请项</el-button>
  </el-row>
      </el-tab-pane>
    </el-tabs>
    <el-form-item>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>

import { useTagsViewStore } from '@/store/modules/tagsView'

defineOptions({ name: 'BpmOALeaveCreate' })

//const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { currentRoute,push } = useRouter() // 路由
import { DepPurchaseApi, DepPurchaseVO } from '@/api/erp/deppurchase'
//引入全局方法  防抖
import debounce from 'lodash/debounce'
//产品查询API和实体
import { ProductApi, ProductVO } from '@/api/spd/product/product'
import { handleTree } from '@/utils/tree'
import {
  // erpCountInputFormatter,
  erpPriceInputFormatter,
  erpPriceMultiply,
  // getSumValue
} from '@/utils'
/** ERP 科室采购申请单 表单 */
//defineOptionss({ name: 'DepPurchaseForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  warehouseId: undefined,
  deptId: undefined,
  orderId: undefined,
  integrateId: undefined,
  remark: undefined,
  status: undefined,
  processInstanceId: undefined,
  depPurchaseItems: [],
})
const depPurchaseItems=ref([])
const formRules = reactive({
  
  
})
const itemRules= reactive({
  productId: [{ required: true, message: '产品编号不能为空', trigger: 'blur' }],
  productPrice: [{ required: true, message: '产品单价不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
  // status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const itemRef = ref() // 表单 Ref
/** 监听合同产品变化，计算合同产品总价 */
watch(
  () => depPurchaseItems.value,
  (val) => {
    if (!val || val.length === 0) {
      return
    }
    // 循环处理
    val.forEach((item) => {
      item.totalProductPrice = erpPriceMultiply(item.productPrice, item.count)
      item.taxPrice = erpPriceMultiply(item.totalProductPrice, item.taxPercent / 100.0)
      if (item.totalProductPrice != null) {
        item.totalPrice = item.totalProductPrice + (item.taxPrice || 0)
      } else {
        item.totalPrice = undefined
      }
    })
  },
  { deep: true }
)

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  const itemvalid = await itemRef.value.validate()
  if (!itemvalid) return
  // 提交请求
  formLoading.value = true
  try {
    depPurchaseItems.value.forEach(element => {
      element.countActual=element.count
      formData.value.depPurchaseItems.push(element)
    });
    const data = { ...formData.value } as unknown as  DepPurchaseVO  

    await DepPurchaseApi.createDepPurchase(data)
    message.success('发起成功')
    emit('success')
    // 关闭当前 Tab
    delView(unref(currentRoute))
    await push({ name: 'DepPurchase' })
  } finally {
    formLoading.value = false
  }
}

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    orderId: undefined,
    supplierId: undefined,
    productId: undefined,
    productUnitId: undefined,
    productUnitName: undefined,
    productStandards: undefined,
    productPrice: undefined,
    count: 1,
    countActual:1,
    totalPrice: undefined,
    remark: undefined,
    productName:''
  }
  row.orderId = formData.orderId
  depPurchaseItems.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  depPurchaseItems.value.splice(index, 1)
}


/** 处理产品变更 */
const onChangeProduct = (productId, row) => {


  // 检查新选择的产品ID是否与上面的产品ID相同
  const currentIndex = depPurchaseItems.value.indexOf(row);
  if (currentIndex > 0) {
    for (let i = 0; i < currentIndex; i++) {
      const previousRow = depPurchaseItems.value[i];
      if (previousRow.productId === productId) {
        ElMessage.error('选择的产品不能相同');
        row.productName = undefined; // 清空当前行的产品ID
        return;
      }
    }
  }

  const product = supplierList.value.find((item) => item.id === productId)
  if (product) {
    row.productName=product.name
    row.productId=product.id
    row.productStandards = product.standard //产品规格
    row.productUnit = product.unitId //产品单位
    row.productUnitId = product.unitId //产品单位id
    row.productUnitName = product.unitName //产品单位
    row.productCategoryId = product.categoryId //产品单位id
    row.productCategoryName = product.categoryName //产品单位
    row.productPrice = product.purchasePrice //产品单价


  }
  // 加载库存
  // setStockCount(row)
}

/** 加载库存 */
// const setStockCount = async (row: any) => {
//   if (!row.productId) {
//     return
//   }
//   const count = await StockApi.getStockCount(row.productId)
//   row.stockCount = count || 0
// }




/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

/**
 * 键入监听方法
 */

 const supplierList = ref<ProductVO[]>([])  // 供应商列表
 const hospitalFilter =(params)=> {
  //判断键入是否有值
  if(params!==""){
    //有值调用防抖方法
    debouncedSearch(params)
  }else{
    //没有键入值，集合为空
    supplierList.value=[]
  }
}
/**
 * 根据键入的值查询产品列表
 */
const productLists=async(params)=>{
  // 加载产品列表
  const supplierData = await ProductApi.getProductSimpleLists(params)
  supplierList.value = handleTree(supplierData, 'id')
}

 // 创建一个防抖函数来处理搜索操作
 const debouncedSearch =debounce((params,delay = 500) => { 
      //定义等待时间
      const timer = ref() 
      // 模拟异步数据获取（例如API调用）
      if(timer.value){
          //清除等待时间
          clearTimeout(timer.value); 
        }
      //等待时间赋值
      timer.value = setTimeout(async() => {
        //调用后端根据键入的值查询产品列表方法
        productLists(params)
      }, delay); // 延迟500毫秒以模拟网络延迟或数据处理时间
  }, 500); // 防抖等待时间为500毫秒 

/** 初始化 */
onMounted(async () => {
})




/** 子表的表单 */
const subTabsName = ref('depPurchaseItem')
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DepPurchaseApi.getDepPurchase(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调


/** 重置表单 */
const resetForm = () => {
  depPurchaseItems.value=[]
  formData.value = {
    id: undefined,
    warehouseId: undefined,
    deptId: undefined,
    orderId: undefined,
    integrateId: undefined,
    remark: undefined,
    status: undefined,
    processInstanceId: undefined,
    depPurchaseItems: [],
  }
  formRef.value?.resetFields()
}



</script>
